package com.sunwayworld.basemodule.coredata.method.validators;

import com.sunwayworld.basemodule.coredata.method.bean.LimsMethodBean;
import com.sunwayworld.basemodule.coredata.method.bean.LimsMethodCertificateBean;
import com.sunwayworld.basemodule.coredata.method.bean.LimsMethodCertificateUserBean;
import com.sunwayworld.basemodule.coredata.method.service.LimsMethodCertificateService;
import com.sunwayworld.basemodule.coredata.test.bean.LimsTestMethodBean;
import com.sunwayworld.basemodule.coredata.test.service.LimsTestMethodService;
import com.sunwayworld.framework.i18n.I18nHelper;
import com.sunwayworld.framework.mybatis.mapper.MatchPattern;
import com.sunwayworld.framework.mybatis.mapper.SearchFilter;
import com.sunwayworld.framework.restful.data.RestJsonWrapperBean;
import com.sunwayworld.framework.spring.annotation.GikamBean;
import com.sunwayworld.framework.validator.data.DataValidator;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import java.util.List;
import java.util.stream.Collectors;

@Repository
@GikamBean
public class LimsMethodCerUserSubmitValidator implements DataValidator {

    @Autowired
    private LimsMethodCertificateService limsMethodCertificateService;

    @Override
    public boolean doValid(Object... args) {
        RestJsonWrapperBean wrapper = (RestJsonWrapperBean) args[0];
        boolean result = true;
        List<LimsMethodCertificateUserBean> methodList = wrapper.parse(LimsMethodCertificateUserBean.class);
        List<Long> idList = methodList.stream().map(LimsMethodCertificateUserBean::getId).collect(Collectors.toList());

        List<LimsMethodCertificateBean> testMethodList = limsMethodCertificateService.selectListByFilter(SearchFilter.instance()
                .match("personId", idList).filter(MatchPattern.OR));
        for(int i=0;i<idList.size();i++){
            Long id=idList.get(i);
            List<LimsMethodCertificateBean> certificateBeans=testMethodList.stream().filter(t -> t.getPersonId().equals(id)).collect(Collectors.toList());
            if (certificateBeans.isEmpty()) {
                this.addConstraintViolation(I18nHelper.getMessage("T_LIMS_METHOD_CERTIFICATE.NOT.EXSIT"));//SOP授权下SOP基础信息未添加！
                return false;
            }
            for(int j=0;j<certificateBeans.size();j++){
                LimsMethodCertificateBean certificateBean=certificateBeans.get(j);
                if (certificateBean.getCertdate()==null||certificateBean.getExpdate()==null) {
                    this.addConstraintViolation(I18nHelper.getMessage("The authorization date was not entered!"));//SOP授权下SOP基础信息未添加！
                    return false;
                }
            }
        }

        return result;
    }
}
